<!-- 不可编辑的【表格】  -->

<template>
  <div class="tableContain">
    <!--编辑显示字段-->
    <div
      style="width:200px;margin-top:3px;margin-bottom:3px;height:30px;margin-left:10px"
      v-show="list =='list'"
    >
      <el-button type="primary" size="small" @click="checkeField">选择显示字段</el-button>
    </div>
    
    <el-table
      class="infotable"
      :row-key="getRowKey"
      border
      :data="tableList"
      tooltip-effect="dark" 
      highlight-current-row
      style="width: 100%;"
      fit
      @select="selectTdClick"
      @select-all="selectAllClick"
      :height="maxHeight-30"
      @row-click="rowClick"
      @row-contextmenu="rowcontextmenu"
      @row-dblclick="rowDblclick"
      @header-click="headerClick"
      :empty-text="emptyText"
      ref="table"
      :header-cell-style="{ background: '#e6eaf3', color: '#000' }"
      :cell-style="cellStyle"
    >
      <!-- 添加多选 -->
      <el-table-column
        type="selection"
        :reserve-selection="true"
        width="36"
        v-if="
        openType == 'list' ||
        openType == 'groupList' || openType == 'typeManage' ||
        operateType == 'selectMany' || openType == 'comboAnalysis'"
      ></el-table-column>
      <el-table-column type="index" label="序号" width="50" fixed></el-table-column>
      <el-table-column v-if="editDetailUrl" label="查看明细" width="100" fixed>
        <template slot-scope="scope">
          <el-button
            type="primary"
            @click="handleEdit(scope.$index, scope.row)"
            size="mini"
            style="margin-left:10px"
          >查看</el-button>
        </template>
      </el-table-column>

      <template v-for="(item1,index) in tableh">
        <!-- 带选择框的 -->
        <el-table-column
          sortable
          :min-width="item1.width ? item1.width:'220'"
          :show-overflow-tooltip="true"
          v-if="item1.type == 'radio' && item1.hidden == 0"
          :label="item1.title"
          :prop="item1.paramName"
          :key="index+'tf'"
          :class-name="item1.paramName == columnProperty ? 'columnClass' : ''"
          :reserve-selection="true"
          :fixed="item1.freeze =='1'? true:false"
        >
          <!-- :fixed="item1.paramName = 'name' ? true:false " -->
          <!-- item1.operateType == 'allowAny' -->
          <template slot="header" slot-scope="scope">
            <el-checkbox
              @change="select"
              style="color: #000"
              :disabled="item1.operateType != 'allowAny'"
            ></el-checkbox>
            {{ scope.column.label }}
          </template>
          <template slot-scope="scope">
            <!-- 单选框的数字类型 -->
            <el-checkbox
              v-if="typeof scope.row[scope.column.property] == 'number'"
              v-model="scope.row[scope.column.property]"
              :true-label="1"
              :false-label="0"
              :disabled="!item1.allow"
            ></el-checkbox>
            <!-- 单选框的字符串类型 -->
            <el-checkbox
              v-else
              v-model="scope.row[scope.column.property]"
              true-label="1"
              false-label="0"
              :disabled="!item1.allow"
            ></el-checkbox>
          </template>
        </el-table-column>

        <!-- min-width="125"  :width="itrm1.type != 'dateTime2' ?'125' :'150'" -->
        <!-- min-width="125"-->
        <el-table-column
          sortable
          :min-width="item1.width"
          v-else-if="item1.type != 'radio' && item1.hidden == 0"
          :label="item1.title"
          :prop="item1.paramName"
          :key="index+'tf2'"
          :show-overflow-tooltip="true"
          :fitHeader="true"
          :autoFit="true"
          :class-name="item1.paramName == columnProperty ? 'columnClass' : ''"
          :fixed="item1.freeze =='1'? true:false"
          v-show="item1.type != 'null' && item1.hidden == '0'"
        >
          <template slot="header">
            <span class="starName">{{ item1.title }}</span>
            <popover
              ref="popoverRef"
              :property="item1.paramName"
              :checkList="checkList"
              @selectChange="selectChange"
              @resetChange="resetChange"
            ></popover>
          </template>
          <!-- 判断单元格是否可编辑（是什么样的编辑类型）-->
          <template slot-scope="scope">
            <span
              style="display:inline-block;padding-right:20px"
            >{{ scope.row[scope.column.property] }}</span>
          </template>


        </el-table-column> 
      </template>
    </el-table>

    <!-- 针对ipad -->
    <div
      v-if="isMenuShow"
      class="menuClass"
      :style="{ top: meunTop + 'px', left: meunLeft + 'px' }"
    >
      <div class="ipadClick" style="border-bottom:1px solid #eee;height:100%;width:100%;disp">
        <div @click="rowDblclick(row)">编 辑</div>
      </div>
    </div>

    <!-- 查看工序明细 -->
    <el-dialog
      :visible.sync="gongxuCon"
      title="工序明细"
      :append-to-body="true"
      width="80%"
      center
      :before-close="dialogMessageClose"
    >
      <div class="table_Info">
        <!-- :cell-style="{'text-align':'center'}" -->
        <el-table
          ref="table"
          :data="gongxuData.paramTable"
          border
          size="mini"
          style="width:100%;"
          :header-cell-style="{'text-align':'center'}"
        >
          <el-table-column type="index" width="auto" label="序号"></el-table-column>
          <el-table-column
            v-for="item in gongxuData.paramTitle"
            :key="item.paramName"
            :prop="item.paramName"
            :label="item.title"
            :show-overflow-tooltip="true"
            min-width="120"
          >
            <!-- <template slot-scope="scope">
              <el-checkbox
                v-if="item.type =='radio'"
                v-model="scope.row[item.paramName]"
                :true-label="1"
                :false-label="0"
                disabled
              ></el-checkbox>
              <span v-if="item.type !='radio'">{{scope.row[item.paramName]}}</span>
            </template>-->
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!--选择显示字段弹框-->
    <select-field
      ref="field"
      :HeaderData="tableHeader"
      :habitUrl="habitUrl"
      @commonClick="commonClick"
    ></select-field>
  </div>
</template>

<script>
import popover from "./input/popover.vue"; // 过滤组件
import SelectField from "./selectfield.vue";
import Sortable from "sortablejs";
export default {
  name: "tableInfo",
  components: {
    popover,
    SelectField
  },
  data() {
    return {
      gongxuCon: false,
      gongxuData: {},
      tableh: [],
      sateColor: {},
      tableList: [], // 表格数据
      isShowTd: true, //【明细】 输入框与文本内容的切换显示
      columnProperty: "", //选中的列属性值
      isCheck: false, //表头的选中状态
      isIndeterminate: true,
      tableHeaderModel: [],
      getRowKey(row) {
        return row.detailId || row.id;
      },
      isMenuShow: false,
      meunTop: 0,
      meunLeft: 0,
      row: {},
      // 表头过滤条件
      rules: {}, // 存放选中字段的过滤条件
      checkList: {} // 存放每个字段的过滤条件
    };
  },
  props: {
    editDetailUrl: {
      type: String,
      default: ""
    },
    habitUrl: {
      type: String,
      default: ""
    },
    tableHeader: {
      type: Array,
      default: () => {
        return [];
      }
    }, //表头数据
    tableData: {
      type: Array,
      default: () => {
        return [];
      }
    }, //表body数据
    maxHeight: {
      type: Number,
      default: 300
    }, // 表格高度 300
    openType: {
      type: String,
      default: ""
    },
    emptyText: {
      type: String,
      default: "暂无数据"
    },
    operateType: {
      type: String,
      default: null
    },
    list: {
      type: String,
      default: null
    },
    nameM: {
      type: String,
      default: null
    }
  },
  watch: {
    tableData: {
      handler(nav) {
        this.isCheck = false;
        // console.log(this.tableList);
        // console.log(nav);
        // console.log(this.tableData);
        this.$nextTick(() => {
          // 重新布局table数据
          this.$refs.table.doLayout();
          this.tableList = nav;
        });
        this.checkList = {};
        if (this.tableData.length != 0) {
          for (let k in this.tableData[0]) {
            this.$set(this.checkList, k, []); // 设置数组对象
          }
          for (let i in this.tableData) {
            for (let k in this.tableData[i]) {
              if (
                this.checkList[k] &&
                this.checkList[k].findIndex(
                  item => item == this.tableData[i][k]
                ) == -1
              ) {
                this.checkList[k].push(this.tableData[i][k]);
              }
            }
          }
        }
        console.log(this.checkList);
      },
      immediate: true,
      deep: true
    },
    tableHeader: {
      immediate: true,
      deep: true,
      handler(val) {
        this.tableh = JSON.parse(JSON.stringify(val));
        this.tableHeader = val;
        this.selectSatetColor();
      }
    },
    tableList: {
      immediate: true,
      deep: true,
      handler(val) {
        this.tableList = val;
      }
    }
  },
  updated() {
    // this.$refs.table.doLayout();
    // console.log(this.$refs.table);
  },
  mounted() {
    // 监听所有的点击事件
    document.getElementsByClassName("tableContain")[0].onclick = e => {
      if (this.isMenuShow == true) {
        this.isMenuShow = false;
      }
    };

    // this.selectSatetColor();
    // console.log(this.tableData)
    // console.log(this.tableHeader)
    // console.log(this.tableh)
    // 列的拖拽初始化
    this.columnDropInit();
  },
  methods: {
    // sortChange(column) {
    //   let searchOrder = {
    //     paramName: column.prop,
    //     order: column.order == "descending" ? "desc" : "asc"
    //   };
    //   this.$emit("changeSort", searchOrder);
    // },

    //清除选中的行数据
    selsChange() {
      this.$refs.table.clearSelection();
    },
    //列拖拽
    columnDropInit() {
      // 第一步，获取列容器
      let domNode = `.${this.nameM} .el-table__header-wrapper tr`;
      const wrapperColumn = document.querySelector(domNode);
      // 第二步，给列容器指定对应拖拽规则
      if (wrapperColumn) {
        this.sortable = Sortable.create(wrapperColumn, {
          animation: 500,
          delay: 0,
          onEnd: event => {
            // 接下来做索引的交换
            let tempHableHeader = [...this.tableh]; // 先存一份临时变量表头数据
            tempHableHeader.splice(
              event.newIndex - 2,
              0,
              tempHableHeader.splice(event.oldIndex - 2, 1)[0]
            ); // 数据处理，获取最新的表格数据

            // 这里一定要先把表头数据清空，然后再下一轮中去赋值，否则会渲染错误
            this.tableh = []; // 大家可以注掉试试哦
            this.$nextTick(() => {
              this.tableh = tempHableHeader;
            });
          }
        });
      }
    },

    // 监听表格中被选中的值
    selectTdClick(row, index) {
      // console.log(this.checkRow); // 当前被选中的全部行数据 {对象型}
      // console.log(index); // 当前选中的值 [数组型]
      this.$emit("selectTdClick", row);
    },
    selectAllClick(row) {
      this.$emit("selectTdClick", row);
    },

    // 行被点击时,将行数据传递给父组件
    // 单点
    rowClick(row) {
      this.$emit("rowClick", row);
    },
    // 双击行数据的时候
    rowDblclick(row) {
      this.$emit("rowDblclick", row);
      if (this.isMenuShow == true) {
        this.isMenuShow = false;
      }
    },
    toScrollTop() {
      this.$nextTick(() => {
        this.$refs.table.bodyWrapper.scrollTop = 0;
      });
    },
    // 选中的列数据
    headerClick(column) {
      console.log(column);
      this.$emit("selectColumnClick", column);
      this.columnProperty = column.property; //选中的列数据字段
    },
    // renderHeader(h, {
    //   column
    // }) {
    //   return h(
    //     'span',
    //     [
    //       h('el-checkbox', {
    //         style: 'display:inline-flex;margin-right:15px;',
    //         on: {
    //           change: this.select
    //         },
    //       }),
    //       h('span', column.label)
    //     ]
    //   )
    // },
    /** 是否勾选表头 */
    select(checked) {
      this.isCheck = checked;
      // 如果checked为true则是勾选了对应的表头
      if (checked) {
        this.tableList.forEach((item, index) => {
          this.tableList[index][this.columnProperty] = 1;
        });
      } else {
        this.tableList.forEach((item, index) => {
          this.tableList[index][this.columnProperty] = 0;
        });
      }
    },
    // 鼠标右击事件
    rowcontextmenu(row, column, event) {
      this.row = row;
      // 导航栏小弹窗
      this.isMenuShow = true;
      this.meunTop = event.clientY - 30;
      this.meunLeft = event.clientX + 10;
    },
    // 【筛选】
    //选中筛选条件的事件
    selectChange(data) {
      console.log(data);
      // 拼接当前字段的 筛选提交
      let property = data["property"];
      let selectList = data["selectList"]; // 选中的字段
      this.$set(this.rules, property, selectList);
      // 重新遍历表格的数据
      this.tableList = this.tableData;
      // 遍历过滤条件
      let items = [];
      // 遍历所有条件
      for (let key in this.rules) {
        let itemsList = [];
        for (let index in this.rules[key]) {
          items = this.tableList.filter(item => {
            return item[key] == this.rules[key][index];
          });
          itemsList = itemsList.concat(items);
        }

        this.tableList = JSON.parse(JSON.stringify(itemsList));
      }
      this.resetCheckList();
    },

    // 筛选的【重置】事件
    resetChange(data) {
      // 清空当前字段的筛选条件
      delete this.rules[data["property"]];
      this.tableList = this.tableData;
      // 再次遍历过滤条件
      let items = [];
      for (let key in this.rules) {
        let itemsList = [];
        for (let index in this.rules[key]) {
          items = this.tableList.filter(item => {
            return item[key] == this.rules[key][index];
          });
          itemsList = itemsList.concat(items);
        }
        this.tableList = JSON.parse(JSON.stringify(itemsList));
      }
      this.resetCheckList();
    },

    // 重新计算字段里面的每个字段的过滤条件
    resetCheckList() {
      for (let k in this.checkList) {
        // 如果表格中存在没有于当前选中的过滤字段一致的，就说明当前的过滤不包涵该字段
        // 重置多选条件
        if (!this.rules.hasOwnProperty(k)) {
          this.checkList[k].length = 0;
        }
      }
      for (let i in this.tableList) {
        for (let k in this.tableList[i]) {
          if (!this.rules.hasOwnProperty(k)) {
            if (
              this.checkList[k].findIndex(
                item => item == this.tableList[i][k]
              ) == -1
            ) {
              this.checkList[k].push(this.tableList[i][k]);
            }
          }
        }
      }
    },
    //打开显示字段选择弹框
    checkeField() {
      this.$refs.field.checkeField();
    },
    // 刷新事件调用父组件
    commonClick(refresh) {
      this.$emit("commonClick", refresh); //将点击的按钮信息传递给父组件
    },
    //请求工序明细信息
    async handleEdit(index, row) {
      this.orgData = JSON.parse(sessionStorage.getItem("orgData"));
      console.log(index, row);
      this.gongxuCon = true;

      let { data: res } = await this.$http.get(
        "/api" + this.editDetailUrl + row.id,
        {
          params: {
            orgId: this.orgData.orgType
          }
        }
      );
      if (res.result) {
        this.gongxuData = res;
      }
      console.log(res);
    },
    //关闭工序查看弹窗
    dialogMessageClose() {
      this.gongxuCon = false;
    },

    //判断排产状态
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (this.sateColor != null) {
        if (column.property == this.sateColor.paramName) {
          let name = this.sateColor.paramName;
          switch (row[name]) {
            case "未确认":
            case "未开工":
            case "未处理":
              return "color: #666"; //灰色
              break;

            case "工艺确认":
            case "质检确认":
            case "已开工":
              return "color: #FFC20D"; //黄色
              break;

            case "计划确认":
            case "在制中":
            case "待完工":
            case "已受理":
              return "color: #F16306"; //橙色
              break;

            case "待完工":
            case "计划确认":
            case "逾期完工":
            case "逾期未完工":
              return "color: #823DBF"; //紫色
              break;

            case "完结订单":
            case "已完结":
              return "color: #15BF4F"; //绿色
              break;

            case "车间确认":
            case "生产完工":
            case "工序完工":
            case "开工中":
              return "color: #0080CF"; //蓝色
              break;

            case "停工":
            case "已挂起":
              return "color: #A41A11"; //红色
              break;
          }
        }
      }
    },
    selectSatetColor() {
      var sateC = {
        paramName: "",
        actionValue: "",
        colorItems: []
      };
      if (this.tableHeader) {
        this.tableHeader.forEach(item => {
          if (item.type == "textColor") {
            (sateC.paramName = item.paramName),
              (sateC.actionValue = item.actionValue),
              (sateC.colorItems = item.colorItems);
          }
        });
      }
      this.sateColor = sateC;
    }
  }
};
</script>
<style lang='scss'>
// 拖拽
.dragClass {
  background: rgba($color: #41c21a, $alpha: 0.5) !important;
}
// 停靠
.ghostClass {
  background: rgba($color: #6cacf5, $alpha: 0.5) !important;
}
// 选择
.chosenClass:hover > td {
  background: rgba($color: #f56c6c, $alpha: 0.5) !important;
}
/*平板*/
@media screen and (min-width: 600px) and (max-width: 960px) {
  .infotable {
    height: 62vh !important;
  }
}
</style>
<style scoped>
.tableContain {
  width: 100%;
  height: 100%;
}

.tableContain p {
  width: 100%;
  height: 100%;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  padding-right: 20px;
}

.tableContain .editInput {
  background-color: #eefefe;
}

.menuClass {
  position: fixed;
  z-index: 999999;
  width: 150px;
  height: 60px;
  box-shadow: 0px 0px 10px 1px rgba(0, 0, 0, 0.2);
  background-color: #409eff;
  border: 1px solid #eee;
  border-radius: 10px;
  padding: 5px 0;
  font-size: 12px;
  box-sizing: border-box;
}
.ipadClick {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 30px;
  color: #ffff;
}

.menuClass > div {
  width: 100%;
  padding: 2px 10px;
  box-sizing: border-box;
}

.menuClass > div:hover {
  color: white;
  background-color: #696bcc;
}
</style>
<style>
.el-table .cell,
.el-table th > .cell {
  white-space: nowrap;
  width: fit-content;
}

.tableContain .el-table .el-table__cell {
  color: #1f1c1c;
  padding: 6px 0;
  box-sizing: border-box;
}

.tableContain .el-table .cell {
  font-size: 14px;
  padding: 0 5px;
  height: 30px;
  line-height: 30px;
  box-sizing: border-box;
  /* display: flex;
  align-items: center;
  width: 100% !important;
  height: 100% !important; */
}

.tableContain .el-input__inner {
  width: 100%;
  height: 30px;
  border: none;
  padding: 0 5px;
  background-color: #f5f7fa;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  box-sizing: border-box;
}

/* 表格单元格 溢出提示 */
.el-tooltip__popper {
  max-width: 150px;
}

.tableContain
  .el-table--striped
  .el-table__body
  tr.el-table__row--striped.current-row
  td,
.el-table__body tr.current-row > td {
  background-color: #e1e6ee !important;
}

.tableContain .el-table tbody tr:hover > td {
  background-color: #e1e6ee !important;
}

.tableContain .el-table__empty-text {
  font-size: 18px;
  font-weight: 700;
}

.columnClass {
  /* border: 1px solid blue; */
  /* border-right: 1px solid blue; */
  background-color: #bdcbec;
}

.el-table__footer tr > td {
  padding: 0 !important;
}

.tableContain .el-table th.el-table__cell .cell span {
  display: inline-block;
}
</style>